<?php

namespace  haoleke\utils;

use think\Response;

class Json
{
    private $status = 200;    //明显是http状态的code，而非status

    public function status($status)
    {
        $this->status = $status;
        return $this;
    }

    //创建响应
    public function make($code, $msg, $data = null, $count = null)
    {
        $res = compact('code', 'msg');
        $res['data'] = $data;
        if ($count){
            $res['count'] = $count;
        }
        return Response::create($res, 'json', $this->status);
    }

    //常用返回,值为字符串默认是失败
    public function go($data)
    {
        if(is_array($data)){
            return $this->success('操作成功', $data);
        }
        if (is_string($data) || !$data) {
            return $this->error('操作失败');
        } else{
            return $this->success('操作成功', $data);
        }
    }

    //操作成功
    public function success($obj = '操作成功', $data = 1, $count = null): Response
    {
        if (!is_string($obj) || is_numeric($obj)) {
            $data = $obj;
            $obj = '操作成功';
        }
        return $this->make(200, $obj, $data, $count);
    }

    //操作错误
    public function error($msg = '操作失败', $data = null): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = '操作失败';
        }
        return $this->make(400, $msg, $data);
    }

}